package org.example.zhihuan.services;

import org.example.zhihuan.services.projectException.AssIdExistException;
import org.example.zhihuan.services.projectException.CompedException;
import org.example.zhihuan.util.Db;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;

public class Complaint {
    private static final int UNCOMPED = 2;//初始值
    private static int COMP_OK = 0; //投诉通过
    private static int COMP_NO = 1; //投诉不通过

    private int compId;
    private int compUserId;            //投诉方
    private int isCompUserId;          //被投诉方
    private String compContent;        //投诉内容
    private int adminId;               //管理员
    private int compState;             //投诉是否受理
    private Date compDate;                  //投诉时间

    private boolean isSaved = false;

    public int getCompId() {
        return compId;
    }

    public int getCompUserId() {
        return compUserId;
    }

    public int getIsCompUserId() {
        return isCompUserId;
    }

    public String getCompContent() {
        return compContent;
    }

    public int getAdminId() {
        return adminId;
    }

    public int getCompState() {
        return compState;
    }

    public Date getCompDate() {
        return compDate;
    }

    public boolean isSaved() {
        return isSaved;
    }


    /**
     * 持久化
     */
    public void save() {
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (isSaved) {
            sb.append("update complaint set ")
                    .append(" compuser_id = ").append(compUserId).append(",")
                    .append(" iscompuser_id = ").append(isCompUserId).append(",")
                    .append(" comp_content = '").append(compContent).append("',")
                    .append(" admin_id = ").append(adminId).append(",")
                    .append(" comp_state = ").append(compState).append(",")
                    .append(" comp_date = '").append(fm.format(compDate)).append("' ")
                    .append("where comp_id = ").append(compId);
        } else {
            sb.append("insert into complaint(comp_id,compuser_id,iscompuser_id,comp_content,admin_id,comp_state,comp_date) values(")
                    .append(compId).append(",").append(compUserId).append(",").append(isCompUserId).append(",'")
                    .append(compContent).append("',").append(adminId).append(",").append(compState).append(",'")
                    .append(fm.format(compDate)).append("')");
            isSaved = true;
        }
        Db.execute(sb.toString());
    }

    /**
     * 投诉的创建
     *
     * @param compUserId
     * @param isCompUserId
     * @param compContent
     * @param compDate
     */
    public static void createComp(int compUserId, int isCompUserId, String compContent, Date compDate) {
        Complaint complaint = new Complaint();
        complaint.compUserId = compUserId;
        complaint.isCompUserId = isCompUserId;
        complaint.compContent = compContent;
        complaint.compDate = compDate;
        complaint.save();
    }

    /**
     * 获取投诉
     *
     * @param compId
     * @return
     */
    public static Complaint getComplaint(int compId) {
        if (!Complaint.compIdExist(compId))
            throw new CompedException("评论不存在");
        Complaint Complaint = new Complaint();
        Db.read("select * from Complaint where comp_id = " + compId, set -> {
            if (set.next()) {
                Complaint.compId = set.getInt("comp_id");
                Complaint.compUserId = set.getInt("compuser_id");
                Complaint.isCompUserId = set.getInt("iscompuser_id");
                Complaint.compContent = set.getString("comp_content");
                Complaint.adminId = set.getInt("admin_id");
                Complaint.compState = set.getInt("comp_state");
                Complaint.compDate = set.getTimestamp("comp_date");
                Complaint.isSaved = true;
            }
            return null;
        });
        return Complaint;
    }

    /**
     * 判断投诉是否存在
     *
     * @param compId
     * @return
     */
    public static boolean compIdExist(int compId) {
        return Db.read("select 1 from complaint where comp_id = " + compId, ResultSet::next);
    }

    /**
     * 投诉的审核
     *
     * @param checkComp
     */
    public void checkComp(boolean checkComp, int adminId) {
        if (compState != UNCOMPED)
            throw new CompedException("无法审核");

        if (checkComp == true) {
            this.adminId = adminId;
            this.compState = COMP_OK;
            this.save();
        } else {
            this.adminId = adminId;
            compState = COMP_NO;
            this.save();
        }
        save();
    }

    public static Map<String, Object> getList(Map<String, Object> map) {
        Map<String, Object> res = new HashMap<>();

        StringBuilder sb = new StringBuilder();
        sb.append(" where true");
        if (map.containsKey("beginCreateAt") && map.containsKey("endCreateAt")) {
            sb.append(" and comp_date between").append("'")
                    .append(map.get("beginCreateAt")).append("'")
                    .append(" and '").append(map.get("endCreateAt")).append("'");
        }

        if (map.containsKey("observesId")) {
            sb.append(" and compuser_id =").append(map.get("observesId"));
        }

        //结果的长度
        int count = Db.read("select count(*) from complaint " + sb.toString(), set -> {
            if (set.next()) return set.getInt(1);
            else return 0;
        });

        int offset = (Integer) map.get("pageCount") * ((Integer) map.get("pageNumber") - 1);

        //结果内容
        List<Map<String, Object>> list = new ArrayList<>();
        Db.read("select cr.*,u.user_name as compuser_name,u2.user_name as iscompuser_name,ad.admin_name from complaint cr"+
                " inner join user u on cr.compuser_id = u.user_id"+
                " inner join user u2 on cr.iscompuser_id = u2.user_id"+
                " inner join admin ad on cr.admin_id = ad.admin_id" +
                sb.toString() + " order by comp_id desc limit " +
                map.get("pageCount") + " offset " + offset, set -> {
            while (set.next()) {
                Map<String, Object> objs = new HashMap<>();
                objs.put("comp_id", set.getInt("comp_id"));
                objs.put("comp_date", set.getDate("comp_date"));
                objs.put("compuser_name", set.getString("compuser_name"));
                objs.put("iscompuser_name", set.getString("iscompuser_name"));
                objs.put("admin_name", set.getString("admin_name"));
                objs.put("compuser_id", set.getInt("compuser_id"));
                objs.put("iscompuser_id", set.getInt("iscompuser_id"));
                list.add(objs);
            }
            return list;
        });
        res.put("count",count);
        res.put("list",list);
        return res;
    }
}
